#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/wait.h>
#include <sys/stat.h>
#include <vector>
using namespace std;

#define PROCESSNUMS 10

typedef void (*task_t)();
vector<task_t> task;
void task1()
{
  cout << "task 1: 刷新野怪" << endl;
}
void task2()
{
  cout << "task 2: 恢复血条" << endl;
}
void task3()
{
  cout << "task 3: 刷新日志" << endl;
}
void task4()
{
  cout << "task 4: 更换场景" << endl;
}
void Init_task() // 初始化任务列表
{
  task.push_back(task1);
  task.push_back(task2);
  task.push_back(task3);
  task.push_back(task4);
}

void menu()
{
  cout << "##############################" << endl;
  cout << "####1. 刷新野怪 2. 恢复血条####" << endl;
  cout << "####3. 刷新日志 4. 更换场景####" << endl;
  cout << "##############################" << endl;
  cout << "please entry@ ";
}

void slaver(int pipefd[])
{
  int cmdnum = 0;
  read(0, &cmdnum, sizeof(int));
  if (cmdnum >= 0 && cmdnum < 4)
    task[cmdnum]();
  else
    cout << "不合法输入！" << endl;
}

void ControlChildProcess(int pipefd[])
{
  int cmdnum = 0;
  menu();
  cin >> cmdnum;
  write(pipefd[1], &cmdnum, sizeof(int));
}

void InitProcessPool()
{
  for (int i = 0; i < PROCESSNUMS; i++)
  {
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    pid_t id = fork();
    if (id == 0)
    {
      // child，负责读
      close(pipefd[1]);
      dup2(pipefd[0], 0);
      // 执行slaver操作
      slaver(pipefd);
      exit(0);
    }
    close(pipefd[0]);
    ControlChildProcess(pipefd);
  }
}
